<?php
namespace App\Http\Controllers\Home;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Components\Tools;
use App\Components\DyToools;
use App\Models\DyModels\Douyin;
use App\Models\UserModels\User;
use App\Components\DySqTools;
use App\Models\ExpModels\Exp;
class DouyinController extends Controller{
	//抖音调用接口方法
	private $clientKey='';
	private $clientSecret='';
	private $url='';
	private $redirectUri='';
	private $scope='';
	private $thirsdUrl="";
	private $thirsdUrlTwo="";
	
	function __construct(Request $request){
        $this->parames = $request->all();
		$this->clientKey=Tools::getOneconfig("/config/third.json",array('douyin','dy_client_key'));
		$this->clientSecret=Tools::getOneconfig("/config/third.json",array('douyin','dy_client_secret'));
		$this->url=Tools::getOneconfig("/config/third.json",array('douyin','dy_url'));
		$this->redirectUri=Tools::getOneconfig("/config/third.json",array('douyin','dy_bank_url'));
		
		$this->scope="video.create,video.delete,video.data,video.list,im.share,video.search,video.search.comment,aweme.share,user_info,following.list,fans.list,fans.check,";
		$this->scope.="renew_refresh_token,mobile_alert,mobile,video.comment,enterprise.data,enterprise.im,item.comment,data.external.user,data.external.item,fans.data,";
		$this->scope.="star_top_score_display,star_tops,star_author_score_display,data.external.sdk_share,data.external.fans_favourite,poi.search,micapp.is_legal,incremental_authorization";
		
		$this->thirsdUrl="http://api.xstatus.cn/douyin/video/comments?token=3440488a80744d30abe1a41f3a7062d5&aweme_id=";
		$this->thirsdUrlTwo="http://api.xstatus.cn/douyin/video/comment/reply?token=3440488a80744d30abe1a41f3a7062d5&aweme_id=";
		$this->thirsdUrlMe="http://139.186.147.106:5000/comment";	//自用的服务器评论抓取地址
	}
	
	//授权公共
	function auth($redirectUri){
		$url = $this->url ."/platform/oauth/connect/?client_key={$this->clientKey}&response_type=code&scope={$this->scope}&redirect_uri={$redirectUri}";
		header("Location:".$url);
	}
	
	
	
	//会员、合伙人授权----------------------------------------------------------------------------------------------------------------------------------------
	function index(){
		$kid=isset($this->parames['kid']) ? intval($this->parames['kid']) : 0;
		$redirectUri=$this->redirectUri . "/douyin/banck&state={$kid}";
		$this->auth($redirectUri);
	}
	//会员、合伙人授权回调  获取access_token
	function banck(){
        $DySqTools=new DySqTools();
		$accessToken=new Douyin();
		$code=isset($this->parames['code']) ? $this->parames['code'] : '';
		$kid=isset($this->parames['state']) ? intval($this->parames['state']) : 0;//用户ID
		if($kid==0){echo "参数错误";exit;}
		$url=$this->url ."/oauth/access_token?client_key={$this->clientKey}&client_secret={$this->clientSecret}&grant_type=authorization_code&code={$code}";
		$data=$this->getJson($url);
		if($data['data']['error_code']==0){
			$re=$this->getUserInfo($data['data']['open_id'],$data['data']['access_token'],$kid);
			if($re){
                $accessToken->saveToken($data['data'],$this->scope,$data['data']['open_id']);
                $DySqTools->getAllInfo($data['data']['open_id'],$data['data']['access_token'],$data['data']['refresh_token']);
				echo "授权成功";
			}else{
				echo "授权失败";
			}
		}else{
			echo $data['data']['description'];
		}
	}
	//获取会员、合伙人信息插入数据库
	function getUserInfo($open_id,$access_token,$kid){
		$accessToken=new Douyin();
		$url=$this->url ."/oauth/userinfo?open_id={$open_id}&access_token={$access_token}";
		$data=$this->getJson($url);
		if($data['data']['error_code']==0){
			return $accessToken->upUserInfo($data['data'],$open_id,$kid);
		}
		return false;
	}
	//达人授权------------------------------------------------------------------------------------------------------------------------------------------------------------
	function warrantInfo(){
		$kid=isset($this->parames['kid']) ? intval($this->parames['kid']) : 0;
		$industry_id=isset($this->parames['industry_id']) ? intval($this->parames['industry_id']) : 0;
		$redirectUri=$this->redirectUri . "/douyin/banck/info&state={$kid}-{$industry_id}";
		$this->auth($redirectUri);
	}
	//达人授权回调
	function banckInfo(){
		$accessToken=new Douyin();
		$code=isset($this->parames['code']) ? $this->parames['code'] : '';
		$state=isset($this->parames['state']) ? $this->parames['state'] : false;//用户ID 行业 id
		$state=explode("-",$state);
		$kid=$state[0];$industry_id=$state[1];
		
		$url=$this->url ."/oauth/access_token?client_key={$this->clientKey}&client_secret={$this->clientSecret}&grant_type=authorization_code&code={$code}";
		$data=$this->getJson($url);
		if($data['data']['error_code']==0){
			$re=$this->getUserInfoTwo($data['data']['open_id'],$data['data']['access_token'],$kid,$industry_id);
			if($re){
				$accessToken->saveToken($data['data'],$this->scope,$data['data']['open_id']);
				echo "授权成功";
			}else{
				echo "授权失败";
			}
		}else{
			echo $data['data']['description'];
		}
	}
	//获取达人信息插入数据库
	function getUserInfoTwo($open_id,$access_token,$kid,$industry_id){
		$accessToken=new Douyin();
		$url=$this->url ."/oauth/userinfo?open_id={$open_id}&access_token={$access_token}";
		$data=$this->getJson($url);
		if($data['data']['error_code']==0){
			return $accessToken->upUserInfoTwo($data['data'],$open_id,$kid,$industry_id);
		}
		return false;
	}
	
	
	
	
	//定时任务 抓取关键词视频  清洗入库--------------------------------------------------------------------------------------------------------------------------------
	function searchVideo(){
		set_time_limit(0);
		$industry=new Douyin();
		$keywordArr=$industry->selectIndAll();//关键词列表
		if($keywordArr){
			foreach($keywordArr as $k=>$v){
				$this->whileVideo(0,$v['name']);
			}
		}
		// echo "<pre/>";print_r($open_token);exit;
	}
	//循环抓取关键词视频
	function whileVideo($cursor=0,$keyword){
		set_time_limit(0);
		$pt_dy_access_token=new Douyin();
		$DyToools=new DyToools();
		$open_token=$pt_dy_access_token->selectAuthAll();//已经授权用户
		$open_id=isset($open_token['open_id']) ? $open_token['open_id'] : '';
		$access_token=isset($open_token['access_token']) ? $open_token['access_token'] : '';
		$refresh_token=isset($open_token['refresh_token']) ? $open_token['refresh_token'] : '';
		
		$url=$this->url ."/video/search?open_id={$open_id}&access_token={$access_token}&cursor={$cursor}&count=20&keyword={$keyword}";
		$data=$this->getJson($url);
		if($data['data']['error_code']==0){
			
			
			if(isset($data['data']['list'])){
				$pt_dy_access_token->saveKeyVideo($data['data']['list'],$keyword);//存入数据库
			}
			//翻页继续调用
			if($data['data']['cursor']>0){
				$this->whileVideo($data['data']['cursor'],$keyword);
			}
			
			
		}elseif($data['data']['error_code']==10008 || $data['data']['error_code']==2190008){//token过期
		
		
			$dataOne=$DyToools->refresh_token($refresh_token);
			if($dataOne['data']['error_code']==0){
				
				
				$pt_dy_access_token->upToken($dataOne['data'],$open_id);//更新Token
				$this->whileVideo($cursor,$keyword);
				
				
			}elseif($dataOne['data']['error_code']==10010){//refresh 过期
			
			
				$dataTwo=$DyToools->renew_refresh_token($refresh_token);
				if($dataTwo['data']['error_code']==0){
					
					$pt_dy_access_token->upRef($dataTwo['data'],$open_id);//更新 refresh
					$this->whileVideo($cursor,$keyword);
					
				}else{
					
					$pt_dy_access_token->upTokenStatus($open_id);//授权过期需用户重新授权 更改授权状态 为 0
					
				}
			}
		}
	}
	
	
	//	查询指定视频数据  （审核视频 或者 已发布的视频最新数据）------------------------------------------------------------------------------------------------------
	//查询要更新的视频 --- 去重 open_id
	function nowVideo(){
		$userVideo=new Douyin();
		$videoList=$userVideo->examineVideo();
		if($videoList){
			foreach($videoList as $k=>$v){
				$this->findVideoList($v['open_id']);
			}
		}
	}
	//查询指定 open_id 的视频数据 及 授权信息
	function findVideoList($open_id){
		$userVideo=new Douyin();
		$videoList=$userVideo->findVideo($open_id);
		if($videoList){
			$item_ids=array(
			    'item_ids'=>array(),
			);
			foreach($videoList as $k=>$v){
				$item_ids["item_ids"][]=$v['item_id'];
			}
			$this->apiVideoData($item_ids,$open_id);
		}
	}
	//上调接口请求查询视频数据
	function apiVideoData($item_ids,$open_id){
		$infoToken=new Douyin();
		$DyToools=new DyToools();
		
		$token=$infoToken->oneTokenInfo($open_id);
		
		$url=$this->url ."/video/data?open_id={$token['open_id']}&access_token={$token['access_token']}";
		$dataList=$this->postJson($url,$item_ids);
		if( isset($dataList['data']['error_code']) && $dataList['data']['error_code']==0 && isset($dataList['data']['list']) ){
			
			//得到视频数据更新到数据库
			$this->upVideoList($dataList['data']['list']);
			
			
		}elseif( isset($dataList['data']['error_code']) && ($dataList['data']['error_code']==10008 || $dataList['data']['error_code']==2190008) ){
			
			
			// access_token 过期
			$dataOne=$DyToools->refresh_token($token['refresh_token']);
			if($dataOne['data']['error_code']==0){
				
				
				//更新数据库的 access_token
				$infoToken->upToken($dataOne['data'],$open_id);
				//重新调用上调接口
				$this->apiVideoData($item_ids,$open_id);
				
				
			}elseif( isset($dataList['data']['error_code']) &&$dataOne['data']['error_code']==10010 ){
				
				
				//refresh_token 过期
				$dataTwo=$DyToools->renew_refresh_token($token['refresh_token']);
				if( isset($dataList['data']['error_code']) &&$dataTwo['data']['error_code']==0 ){
					
					
					//更新数据库的 refresh_token
					$infoToken->upRef($dataTwo['data'],$open_id);
					//重新调用上调接口
					$this->apiVideoData($item_ids,$open_id);
					
					
				}else{
					$infoToken->upTokenStatus($open_id);//授权过期需用户重新授权 更改授权状态 为 0
				}
			}
		}
	}
	//视频数据更新 //抖音接口修改了需要修改
	function upVideoList($data){
		$upVideo=new Douyin();
		if($data){
			foreach($data as $k=>$v){
				$status=1;$remark="";
				if($v['is_reviewed'] && $v['video_status']==5){
					$status=2;
				}elseif($v['is_reviewed'] && $v['video_status']==6){
                    $status=2;
                }elseif($v['is_reviewed'] && $v['video_status']==7){
                    $status=2;
                }elseif($v['is_reviewed'] && $v['video_status']==2){
					$remark="不宜公开";
				}
				$arr=array(
					'title'=>htmlspecialchars($v['title'],ENT_QUOTES),
					'talk'=>'',
					'is_reviewed'=>$v['is_reviewed'],
					'is_top'=>$v['is_top'],
					'video_status'=>$v['video_status'],
					'status'=>$status,
					'update_time'=>date('Y-m-d H:i:s',time()),
					'comment_count'=>$v['statistics']['comment_count'],
					'digg_count'=>$v['statistics']['digg_count'],
					'download_count'=>$v['statistics']['download_count'],
					'play_count'=>$v['statistics']['play_count'],
					'share_count'=>$v['statistics']['share_count'],
					'forward_count'=>$v['statistics']['forward_count'],
					'remark'=>$remark,
				);
				if($status==2){
					$arr['cover']=$v['cover'];
					$arr['share_url']=$v['share_url'];
				}
				if($v['is_reviewed']){
					$upVideo->upVideoInfo($arr,$v['item_id']);
				}
			}
		}
	}

	
	// 定时更新授权用户信息------------------------------------------------------------------------------------------------------
	function saveUserInfo(){
		$user=new User();
		$dataList=$user->selectUser();
		if($dataList){
			foreach($dataList as $k=>$v){
				$this->dyUserInfo($v['open_id']);
			}
		}
	}
	function dyUserInfo($open_id){
		$user=new User();
		$infoToken=new Douyin();
		$DyToools=new DyToools();
		$token=$user->findToken($open_id);
		$url=$this->url ."/oauth/userinfo?open_id={$open_id}&access_token={$token['access_token']}";
		$data=$this->getJson($url);
		if( isset($data['data']['error_code']) && $data['data']['error_code']==0 ){
			
			//更新授权用户信息
			$user->upDyUserInfo($data['data'],$open_id);

		}elseif( isset($data['data']['error_code']) && $data['data']['error_code']==10008 || $data['data']['error_code']=2190008 ){
			
			// access_token 过期
			$dataOne=$DyToools->refresh_token($token['refresh_token']);
			if( isset($dataOne['data']['error_code']) && $dataOne['data']['error_code']==0 ){
				
				$infoToken->upToken($dataOne['data'],$open_id);//更新Token
				$this->dyUserInfo($open_id);
				
			}elseif( isset($dataOne['data']['error_code']) && $dataOne['data']['error_code']==10010 ){
				
				//refresh_token 过期
				$dataTwo=$DyToools->renew_refresh_token($token['refresh_token']);
				if( isset($dataTwo['data']['error_code']) && $dataTwo['data']['error_code']==0 ){
					
					$infoToken->upRef($dataTwo['data'],$open_id);//更新refresh_token
					$this->dyUserInfo($open_id);
					
				}else{
					$infoToken->upTokenStatus($open_id);//授权过期需用户重新授权 更改授权状态 为 0
				}
			}
			
		}
	}
    //--------------------------定时更新同城拓客的视频信息-----------------------------------------------
    function saveExpVideoInfo(){
        $sExp=new Exp();
        $datelist=$sExp->selectUser();//获取开启状态中的视频的数据
        //  print_r($datelist);exit();
        if($datelist){
            foreach($datelist as $k=>$v){
                $this->dyExpInfo($v['open_id']);
            }
        }
    }

    //查询指定 open_id 的视频数据 及 授权信息
    function dyExpInfo($open_id){
        $sExp=new Exp();
        $videoList=$sExp->findVideo($open_id);
        if($videoList){
            $item_ids=array(
                'item_ids'=>array(),
            );
            foreach($videoList as $k=>$v){
                $item_ids["item_ids"][]=$v['item_id'];
            }
            $this->apiExpVideoData($item_ids,$open_id);
        }
    }
    //上调接口请求查询视频数据
    function apiExpVideoData($item_ids,$open_id){
        $infoToken=new Douyin();
        $DyToools=new DyToools();

        $token=$infoToken->oneTokenInfo($open_id);

        $url=$this->url ."/video/data?open_id={$token['open_id']}&access_token={$token['access_token']}";
        $dataList=$this->postJson($url,$item_ids);
        if( isset($dataList['data']['error_code']) && $dataList['data']['error_code']==0 && isset($dataList['data']['list']) ){

            //得到视频数据更新到数据库
            $this->upEXPVideoList($dataList['data']['list']);


        }elseif( isset($dataList['data']['error_code']) && ($dataList['data']['error_code']==10008 || $dataList['data']['error_code']==2190008) ){


            // access_token 过期
            $dataOne=$DyToools->refresh_token($token['refresh_token']);
            if($dataOne['data']['error_code']==0){

                //更新数据库的 access_token
                $infoToken->upToken($dataOne['data'],$open_id);
                //重新调用上调接口
                $this->apiExpVideoData($item_ids,$open_id);


            }elseif( isset($dataList['data']['error_code']) &&$dataOne['data']['error_code']==10010 ){


                //refresh_token 过期
                $dataTwo=$DyToools->renew_refresh_token($token['refresh_token']);
                if( isset($dataList['data']['error_code']) &&$dataTwo['data']['error_code']==0 ){


                    //更新数据库的 refresh_token
                    $infoToken->upRef($dataTwo['data'],$open_id);
                    //重新调用上调接口
                    $this->apiExpVideoData($item_ids,$open_id);


                }else{
                    $infoToken->upTokenStatus($open_id);//授权过期需用户重新授权 更改授权状态 为 0
                }
            }
        }
    }
    //视频数据更新
    function upEXPVideoList($data){
        $upVideo=new Douyin();
        if($data){
            foreach($data as $k=>$v){
                $status=1;$remark="";
                if($v['is_reviewed'] && $v['video_status']==1){
                    $status=2;
                }elseif($v['is_reviewed'] && $v['video_status']==2){
                    $remark="不宜公开";
                }
                $arr=array(
                    'title'=>htmlspecialchars($v['title'],ENT_QUOTES),
                    'talk'=>'',
//                    'is_reviewed'=>$v['is_reviewed'],
                    'is_top'=>$v['is_top'],
//                    'video_status'=>$v['video_status'],
                    'status'=>$status,
                    'update_time'=>date('Y-m-d H:i:s',time()),
                    'comment_count'=>$v['statistics']['comment_count'],
                    'digg_count'=>$v['statistics']['digg_count'],
                    'download_count'=>$v['statistics']['download_count'],
                    'play_count'=>$v['statistics']['play_count'],
                    'share_count'=>$v['statistics']['share_count'],
                    'forward_count'=>$v['statistics']['forward_count'],
                    'remark'=>$remark,
                );
//                if($status==2){
//                    $arr['cover']=$v['cover'];
//                    $arr['share_url']=$v['share_url'];
//                }
                if($v['is_reviewed']){
                    $upVideo->upExpVideoInfo($arr,$v['item_id']);
                }
            }
        }
    }

















    //get请求
	function getJson($url){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
		curl_setopt($ch, CURLOPT_TIMEOUT,60);//连接后等待时间
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);//连接前等待时间
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);//为true，则会跟踪爬取重定向页面，否则，不会跟踪重定向页面
		curl_setopt($ch, CURLOPT_ENCODING, "");//返回乱码处理
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		$output = curl_exec($ch);
		curl_close($ch);
		return json_decode($output, true);
	}
	//post请求
	function postJson($url, $data = array()){
		//初始化
		$curl = curl_init();
		//设置抓取的url
		curl_setopt($curl, CURLOPT_URL, $url);
		//设置头文件的信息作为数据流输出
		curl_setopt($curl, CURLOPT_HEADER, 0);
		//超时时间
		curl_setopt($curl, CURLOPT_TIMEOUT,60);
		//设置获取的信息以文件流的形式返回，而不是直接输出。
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		//设置post方式提交
		curl_setopt($curl, CURLOPT_POST, 1);
		//设置post数据
		curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($curl, CURLOPT_HTTPHEADER, array(
			'Content-Type: application/json',
			'Content-Length: ' . strlen(json_encode($data)))
		);

		//执行命令
		$json = curl_exec($curl);
		//关闭URL请求
		curl_close($curl);
		return json_decode($json, true);
	}
}